<template>
  <view class="my-select">
    <view class="my-select-item-box">
      <view class="my-input">
        <u-input
          v-model="name"
          readonly
          class="input"
          @click.native.stop="open"
          :placeholder="placeholder"
          :clearable="clearable"
        >
          <template slot="suffix">
            <view class="icon">
              <uni-icons
                v-if="name && clearable"
                @click.native.stop="del"
                type="clear"
                color="#c0c4cc"
                size="24"
              />
              <uni-icons
                v-else
                style="top: 14rpx"
                :type="pickerValue ? 'top' : 'bottom'"
                size="14"
                color="#999"
              />
            </view>
          </template>
        </u-input>
      </view>
    </view>

    <u-datetime-picker
      ref="datetimePicker"
      :show="pickerValue"
      v-model="date"
      @close="() => (pickerValue = false)"
      @cancel="() => (pickerValue = false)"
      @confirm="bindPickerChange"
      :formatter="formatter"
      :mode="mode"
    ></u-datetime-picker>
  </view>
</template>
<script>
export default {
  props: {
    value: String,
    placeholder: String,
    clearable: {
      type: Boolean,
      default: true,
    },
    mode: {
      type: String,
      default: "date",
    },
  },
  data() {
    return {
      pickerValue: false,
      name: "",
      array: [],
      date:
        this.name ||
        this.$dayjs(new Date()).format(
          this.mode === "date" ? "YYYY-MM-DD" : "YYYY-MM-DD HH:mm:ss"
        ),
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val, old) {
        this.name = val;
      },
    },
  },
  methods: {
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      }
      if (type === "month") {
        return `${value}月`;
      }
      if (type === "day") {
        return `${value}日`;
      }
      return value;
    },
    getOption() {
      const that = this;
      //   return fetch("get", "/jeecg-boot/miniprogram/ship/page", {
      //     pageNo: 1,
      //     pageSize: 100,
      //   }).then((data) => {
      //     that.array = [];
      //   });
    },
    open() {
      this.pickerValue = true;
    },
    del() {
      this.name = "";
      this.id = "";
      this.$emit("input", this.id);
      this.$emit("change", this.id);
    },
    bindPickerChange(val) {
      this.pickerValue = false;
      this.name = this.$dayjs(val.value).format(
        this.mode === "date" ? "YYYY-MM-DD" : "YYYY-MM-DD HH:mm:ss"
      );
      this.$emit("input", this.name);
      this.$emit("change", this.name);
    },
  },
};
</script>
<style lang="scss" scoped>
.my-select {
  width: 100%;
}

.my-select-item-box {
  position: relative;
}

.my-input {
  position: relative;
}
</style>
